<template>
    <div class="dialog">
        
        <div class="dialog_default" @click="open()">
            <slot name="trigger"></slot>
        </div>
        
        
        <el-dialog
            v-model="visible"
            :width="props.width"
            :class="props.customClass"
            :close-on-click-modal="props.clickModalClose"
            :append-to-body="true"
            @closed="close"
            :show-close="props.showClose"
            :center="props.center">
            
            
            <!-- 弹窗内容 -->
            <template v-if="props.title" #header>
                <p class="mb-2">{{ props.title }}</p>
                <div class=" h-2 border-b  border-opacity-20"/>
            </template>
            
            
            <slot>{{ props.content }}</slot>
            
            
            <template #footer>
                <div class="dialog-footer" v-if="props.showFooter">
                    <el-button v-if="props.cancelButtonText" @click="handleEvent('cancel')">
                        {{ props.cancelButtonText }}
                    </el-button>
                    
                    <el-button v-if="props.confirmButtonText" type="primary"
                               @click="handleEvent('confirm')"
                    >
                        {{ props.confirmButtonText }}
                    </el-button>
                </div>
            </template>
        
        
        </el-dialog>
    </div>


</template>

<script setup lang="ts">


interface PopupProps {
    showClose?: boolean
    title?: string
    content?: string
    confirmButtonText?: string | boolean
    cancelButtonText?: string | boolean
    width?: string
    disabled?: boolean
    async?: boolean
    clickModalClose?: boolean
    center?: boolean
    customClass?: string
    showFooter?: boolean
}

const props = withDefaults(defineProps<PopupProps>(), {
    showClose: true,
    class: '',
    // 弹窗标题
    title: '',
    // 弹窗内容
    content: '',
    // 确认按钮内容
    confirmButtonText: '确定',
    // 取消按钮内容
    cancelButtonText: '取消',
    // 弹窗的宽度
    width: '400px',
    // 是否禁用
    disabled: false,
    // 是否开启异步关闭
    async: false,
    // 点击遮罩层关闭对话窗口
    clickModalClose: false,
    // 是否居中布局
    center: false,
    customClass: '',
    showFooter: true
})

// 是否打开弹窗
const visible = ref(false)

const emits = defineEmits(['confirm', 'cancel', 'close', 'open']);


/**
 * 处理事件
 *
 * @param type
 */
function handleEvent(type: 'confirm' | 'cancel') {
    emits(type)
    
    if (!props.async || type === 'cancel') {
        close()
    }
}


/**
 * 关闭
 */
function close() {
    visible.value = false
    nextTick(() => {
        emits('close')
        
    })
}


/**
 * 打开
 */
function open() {
    if (props.disabled) {
        return
    }
    visible.value = true
}

provide('visible', visible)


defineExpose({
    open,
    close
})


</script>
